// pages/home/home.js
const utils = require('../../utils/util.js')

Page({
  data: {
    // 工资显示数据
    monthlySalary: '¥0.00',
    todaySalary: '¥0.00',
    todaySalaryBeforeTax: '¥0.00',
    monthlyEarned: '¥0.00',
    payDate: '1',
    yearlySalary: '¥0.00',
    yearlyBonus: '¥0.00',
    bonusProgress: '¥0.00',
    
    // 进度数据
    monthlyProgress: 0,
    bonusProgressPercent: 0,
    daysToPayday: 0,
    
    // 五险一金相关
    showInsurance: false,
    insuranceInfo: null,
    afterTaxMonthlySalary: '¥0.00',
    afterTaxTodaySalary: '¥0.00',
    totalDeduction: '¥0.00',
    
    // 状态控制
    loading: false
  },

  /**
   * 页面加载时初始化
   */
  onLoad: function (options) {
    this.updateSalaryDisplay()
    
    // 每分钟更新一次显示
    this.timer = setInterval(() => {
      this.updateSalaryDisplay()
    }, 60000)
  },

  /**
   * 页面卸载时清理资源
   */
  onUnload: function () {
    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer)
    }
  },

  /**
   * 页面显示时更新数据
   */
  onShow: function () {
    this.updateSalaryDisplay()
  },

  /**
   * 更新工资显示
   */
  updateSalaryDisplay: function () {
    try {
      const salaryInfo = utils.calculateSalaryInfo()
      
      // 更新基本工资信息
      this.updateBasicSalaryInfo(salaryInfo)
      
      // 更新年终奖进度
      this.updateBonusProgress(salaryInfo)
      
    } catch (error) {
      console.error('更新工资显示失败:', error)
      utils.showToast('更新失败，请重试', 'error')
    }
  },

  /**
   * 更新基本工资信息
   */
  updateBasicSalaryInfo: function (salaryInfo) {
    // 检查是否启用了五险一金
    const showInsurance = salaryInfo.insurance !== null && salaryInfo.insurance.total.personal > 0
    
    // 计算进度数据
    const monthlyProgress = this.calculateMonthlyProgress(salaryInfo)
    const daysToPayday = this.calculateDaysToPayday(salaryInfo.payDate)
    
    // 计算今日工资税前金额
    const todaySalaryBeforeTax = this.calculateTodaySalaryBeforeTax(salaryInfo)
    
    this.setData({
      monthlySalary: utils.formatCurrency(salaryInfo.monthlySalary),
      todaySalary: utils.formatCurrency(salaryInfo.todaySalary),
      todaySalaryBeforeTax: utils.formatCurrency(todaySalaryBeforeTax),
      monthlyEarned: utils.formatCurrency(salaryInfo.monthlySalaryEarned),
      payDate: salaryInfo.payDate,
      yearlySalary: utils.formatCurrency(salaryInfo.yearlySalary),
      yearlyBonus: utils.formatCurrency(salaryInfo.yearlyBonus),
      monthlyProgress: monthlyProgress,
      daysToPayday: daysToPayday,
      showInsurance: showInsurance,
      insuranceInfo: salaryInfo.insurance,
      afterTaxMonthlySalary: salaryInfo.afterTaxMonthlySalary ? utils.formatCurrency(salaryInfo.afterTaxMonthlySalary) : '¥0.00',
      afterTaxTodaySalary: showInsurance ? utils.formatCurrency(salaryInfo.todaySalary) : '¥0.00',
      totalDeduction: showInsurance ? utils.formatCurrency(salaryInfo.insurance.total.personal) : '¥0.00'
    })
  },

  /**
   * 更新年终奖进度
   */
  updateBonusProgress: function (salaryInfo) {
    const today = new Date()
    const yearStart = new Date(today.getFullYear(), 0, 1)
    const yearEnd = new Date(today.getFullYear(), 11, 31)
    const settings = utils.getStoredSettings()
    
    const yearWorkedDays = utils.calculateWorkdays(yearStart, today, settings.includeWeekends)
    const yearTotalWorkdays = utils.calculateWorkdays(yearStart, yearEnd, settings.includeWeekends)
    
    const bonusProgress = yearTotalWorkdays > 0 ? (yearWorkedDays / yearTotalWorkdays) * salaryInfo.yearlyBonus : 0
    const bonusProgressPercent = yearTotalWorkdays > 0 ? Math.round((yearWorkedDays / yearTotalWorkdays) * 100) : 0
    
    this.setData({
      bonusProgress: utils.formatCurrency(bonusProgress),
      bonusProgressPercent: bonusProgressPercent
    })
  },

  /**
   * 刷新数据
   */
  refreshData: function () {
    this.setData({ loading: true })
    
    // 模拟加载延迟
    setTimeout(() => {
      this.updateSalaryDisplay()
      this.setData({ loading: false })
      utils.showToast('数据已刷新')
    }, 800)
  },

  /**
   * 分享功能
   */
  shareData: function () {
    const salaryInfo = utils.calculateSalaryInfo()
    const shareText = this.generateShareText(salaryInfo)

    // 设置剪贴板内容
    wx.setClipboardData({
      data: shareText,
      success: () => {
        utils.showToast('工资信息已复制到剪贴板')
      },
      fail: () => {
        utils.showToast('复制失败，请手动复制', 'error')
      }
    })
  },

  /**
   * 生成分享文本
   */
  generateShareText: function (salaryInfo) {
    return `🐂🐎时钟工资信息\n\n` +
           `月薪: ${utils.formatCurrency(salaryInfo.monthlySalary)}\n` +
           `今日已得: ${utils.formatCurrency(salaryInfo.todaySalary)}\n` +
           `本月已得: ${utils.formatCurrency(salaryInfo.monthlySalaryEarned)}\n` +
           `年薪: ${utils.formatCurrency(salaryInfo.yearlySalary)}\n` +
           `发薪日: 每月${salaryInfo.payDate}号\n` +
           `年终奖: ${utils.formatCurrency(salaryInfo.yearlyBonus)}\n\n` +
           `精准计算你的每一份努力 💪`
  },

  /**
   * 显示五险一金详情
   */
  showInsuranceDetails: function () {
    if (!this.data.insuranceInfo) return
    
    const insurance = this.data.insuranceInfo
    const details = this.generateInsuranceDetails(insurance)
    
    wx.showModal({
      title: '五险一金详情',
      content: details,
      showCancel: false,
      confirmText: '知道了'
    })
  },

  /**
   * 生成五险一金详情文本
   */
  generateInsuranceDetails: function (insurance) {
    let details = `🛡️ 五险一金详情\n\n`
    details += `缴纳基数: ${utils.formatCurrency(insurance.base)}\n\n`
    
    // 添加各项保险详情
    for (const [key, item] of Object.entries(insurance.items)) {
      details += `${item.name}:\n`
      details += `  公司: ${item.companyRate}% (${utils.formatCurrency(item.companyAmount)})\n`
      details += `  个人: ${item.personalRate}% (${utils.formatCurrency(item.personalAmount)})\n\n`
    }
    
    // 添加合计信息
    details += `合计:\n`
    details += `  公司承担: ${utils.formatCurrency(insurance.total.company)}\n`
    details += `  个人承担: ${utils.formatCurrency(insurance.total.personal)}\n`
    details += `  总计: ${utils.formatCurrency(insurance.total.overall)}\n\n`
    
    // 添加收入信息
    details += `税后月薪: ${this.data.afterTaxMonthlySalary}\n`
    details += `个人实际收入: ${utils.formatCurrency(this.data.monthlySalary.replace('¥', '') - insurance.total.personal)}`
    
    return details
  },

  /**
   * 计算本月进度
   */
  calculateMonthlyProgress: function (salaryInfo) {
    if (salaryInfo.monthlySalary <= 0) return 0
    return Math.round((salaryInfo.monthlySalaryEarned / salaryInfo.monthlySalary) * 100)
  },

  /**
   * 计算距离发薪日的天数
   */
  calculateDaysToPayday: function (payDate) {
    const today = new Date()
    const currentDay = today.getDate()
    
    // 如果今天已经过了发薪日，计算到下个月发薪日的天数
    if (currentDay > payDate) {
      const nextMonth = new Date(today.getFullYear(), today.getMonth() + 1, payDate)
      const diffTime = nextMonth - today
      return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    } else {
      // 计算到本月发薪日的天数
      const payDay = new Date(today.getFullYear(), today.getMonth(), payDate)
      const diffTime = payDay - today
      return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    }
  },

  /**
   * 计算今日工资税前金额
   */
  calculateTodaySalaryBeforeTax: function (salaryInfo) {
    const settings = utils.getStoredSettings()
    const today = new Date()
    const monthStart = new Date(today.getFullYear(), today.getMonth(), 1)
    const monthEnd = new Date(today.getFullYear(), today.getMonth() + 1, 0)
    
    const monthTotalWorkdays = utils.calculateWorkdays(monthStart, monthEnd, settings.includeWeekends)
    const dailyWage = monthTotalWorkdays > 0 ? salaryInfo.monthlySalary / monthTotalWorkdays : 0
    
    return utils.calculateTodaySalary(today, dailyWage, settings.includeWeekends)
  },

  /**
   * 显示今日收入明细
   */
  showTodayBreakdown: function () {
    const breakdown = this.generateTodayBreakdown()
    wx.showModal({
      title: '今日收入明细',
      content: breakdown,
      showCancel: false,
      confirmText: '知道了'
    })
  },

  /**
   * 生成今日收入明细
   */
  generateTodayBreakdown: function () {
    let breakdown = '📊 今日收入明细\n\n'
    breakdown += `税前收入: ${this.data.todaySalaryBeforeTax}\n`
    breakdown += `税后收入: ${this.data.todaySalary}\n`
    
    if (this.data.showInsurance) {
      const beforeTax = parseFloat(this.data.todaySalaryBeforeTax.replace('¥', ''))
      const afterTax = parseFloat(this.data.todaySalary.replace('¥', ''))
      breakdown += `五险一金扣除: ${utils.formatCurrency(beforeTax - afterTax)}\n`
    }
    
    breakdown += `\n💡 工作时间: 8:00-18:00\n`
    breakdown += `📱 收入按工作时间比例计算`
    
    return breakdown
  },

  /**
   * 显示月薪明细
   */
  showMonthlyBreakdown: function () {
    const breakdown = this.generateMonthlyBreakdown()
    wx.showModal({
      title: '月薪明细',
      content: breakdown,
      showCancel: false,
      confirmText: '知道了'
    })
  },

  /**
   * 生成月薪明细
   */
  generateMonthlyBreakdown: function () {
    let breakdown = '💰 月薪明细\n\n'
    breakdown += `月薪: ${this.data.monthlySalary}\n`
    
    if (this.data.showInsurance) {
      breakdown += `税后月薪: ${this.data.afterTaxMonthlySalary}\n`
      breakdown += `五险一金: ${this.data.totalDeduction}\n`
    }
    
    breakdown += `\n📅 发薪日: 每月${this.data.payDate}号\n`
    breakdown += `⏰ 距离发薪日还有${this.data.daysToPayday}天`
    
    return breakdown
  },

  /**
   * 显示本月已得明细
   */
  showMonthlyEarnedBreakdown: function () {
    const breakdown = this.generateMonthlyEarnedBreakdown()
    wx.showModal({
      title: '本月已得明细',
      content: breakdown,
      showCancel: false,
      confirmText: '知道了'
    })
  },

  /**
   * 生成本月已得明细
   */
  generateMonthlyEarnedBreakdown: function () {
    let breakdown = '📈 本月已得明细\n\n'
    breakdown += `本月已得: ${this.data.monthlyEarned}\n`
    breakdown += `月薪总额: ${this.data.monthlySalary}\n`
    breakdown += `完成进度: ${this.data.monthlyProgress}%\n\n`
    
    if (this.data.showInsurance) {
      breakdown += `💡 已扣除五险一金费用\n`
    }
    
    breakdown += `📱 按实际工作天数计算`
    
    return breakdown
  },

  /**
   * 显示年薪明细
   */
  showYearlyBreakdown: function () {
    const breakdown = this.generateYearlyBreakdown()
    wx.showModal({
      title: '年薪明细',
      content: breakdown,
      showCancel: false,
      confirmText: '知道了'
    })
  },

  /**
   * 生成年薪明细
   */
  generateYearlyBreakdown: function () {
    let breakdown = '💎 年薪明细\n\n'
    breakdown += `年薪: ${this.data.yearlySalary}\n`
    breakdown += `月薪部分: ${this.data.monthlySalary}\n`
    breakdown += `年终奖: ${this.data.yearlyBonus}\n\n`
    
    breakdown += `💡 年薪 = 月薪 × 12 + 年终奖`
    
    return breakdown
  },

  /**
   * 显示年终奖明细
   */
  showBonusBreakdown: function () {
    const breakdown = this.generateBonusBreakdown()
    wx.showModal({
      title: '年终奖进度明细',
      content: breakdown,
      showCancel: false,
      confirmText: '知道了'
    })
  },

  /**
   * 生成年终奖明细
   */
  generateBonusBreakdown: function () {
    let breakdown = '🏆 年终奖进度明细\n\n'
    breakdown += `年终奖总额: ${this.data.yearlyBonus}\n`
    breakdown += `已获得: ${this.data.bonusProgress}\n`
    breakdown += `完成进度: ${this.data.bonusProgressPercent}%\n\n`
    
    breakdown += `💡 按年度工作天数比例计算\n`
    breakdown += `📅 从1月1日开始计算`
    
    return breakdown
  },

  /**
   * 分享到好友
   */
  onShareAppMessage: function () {
    return {
      title: '牛马时钟 - 工资计算器',
      path: '/pages/home/home',
      imageUrl: '/images/share.png'
    }
  }
})